package cn.xw.controller;

import cn.xw.entity.User;
import cn.xw.utils.jwtTools.JwtHSUtils;
import cn.xw.utils.jwtTools.PayloadInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录Controller
 *
 * @author Anhui OuYang
 * @version 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/user")
public class LoginController {

    /***
     * 跳转Login.html页面
     * @return 资源跳转
     */
    @GetMapping(value = "/jumpLogin")
    public @ResponseBody ModelAndView loginPath() {
        return new ModelAndView("login");
    }


    /***
     * 用户登录
     * @param user 登录人账号密码
     */
    @PostMapping("/login")
    public String login(User user, HttpServletResponse response) {
        // 假设都会登录成功
        log.info("登录成功：{}", user);
        // 登录成功后生成token认证信息，后期返回给前端
        // 查询用户信息（假设已经查询了）
        User user1 = new User(10, "张三", 22, "安徽六安", user.getAccount(), "xxx");
        // 调用Token加密
        // 初始化Token信息
        PayloadInfo<User> payloadInfo = new PayloadInfo<>();
        payloadInfo.setIss("http://127.0.0.1:8881/test");
        payloadInfo.setSub("用户信息");
        payloadInfo.setClaim(user1);
        String tokenStr = JwtHSUtils.generateJwtToken(payloadInfo);
        log.info("生成的Token信息为：{}", tokenStr);

        //把token设置到响应头信息
        response.setHeader("Authorization", "Bearer " + tokenStr);
        return "{'code':200,'message':'成功登录'}";
    }

    /***
     * 获取当前用户信息（需要校验权限）
     * @return User
     */
    @GetMapping("/getUserInfo")
    public User getUserInfo(HttpServletRequest request) {
        PayloadInfo<User> userPayloadInfo = JwtHSUtils
                .analysisJwtToken(request.getHeader("Authorization"), User.class);
        assert userPayloadInfo != null;
        return userPayloadInfo.getClaim();
    }
}
